package com.mgface;

/**
 * @author wanyuxiang
 * @version 1.0
 * @project spring-boot-oauth2-system
 * @create 2020-05-22 14:16
 **/
public class MyBitmap {
    private long[] words;
    private int size;

    public MyBitmap(int size) {
        this.size = size;
        this.words = new long[(getWordIndex(size - 1) + 1)];
    }

    private int getWordIndex(int bitIndex) {
        //右移6位，相当于除以64
        return bitIndex >> 6;
    }

    public void setBit(int bitIndex) {
        if (bitIndex < 0 || bitIndex > size - 1) {
            throw new IndexOutOfBoundsException(" 超过Bitmap有效范围");
        }
        int wordIndex = getWordIndex(bitIndex);
        words[wordIndex] |= (1L << bitIndex); //long 63位溢出之后减去63位长度即可
    }

    /**
     * 判断Bitmap某一位的状态
     *
     * @param bitIndex 位图的第bitIndex位
     */


    public boolean getBit(int bitIndex) {
        if (bitIndex < 0 || bitIndex > size - 1) {
            throw new IndexOutOfBoundsException(" 超过Bitmap有效范围");

        }
        int wordIndex = getWordIndex(bitIndex);
        return (words[wordIndex] & (1L << bitIndex)) != 0;
    }

    public static void main(String[] args) {
        MyBitmap bitMap = new MyBitmap(128);
        System.out.println(bitMap.words.length);
        bitMap.setBit(65);
    }

}
